import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:family_app/src/features/secure_vault/models/vault_item_model.dart';
import 'package:family_app/src/features/secure_vault/services/secure_vault_service.dart';

/// u5f53u524du9009u62e9u7684u7c7bu578bu63d0u4f9bu8005
final selectedVaultTypeProvider = StateProvider<VaultItemType?>((ref) => null);

/// u641cu7d22u67e5u8be2u63d0u4f9bu8005
final searchQueryProvider = StateProvider<String>((ref) => '');

/// u79c1u5bc6u4fe1u606fu9879u5217u8868u63d0u4f9bu8005
final vaultItemsProvider = FutureProvider<List<VaultItemModel>>((ref) async {
  final secureVaultService = ref.watch(secureVaultServiceProvider);
  final selectedType = ref.watch(selectedVaultTypeProvider);
  final searchQuery = ref.watch(searchQueryProvider);

  // u5982u679cu6709u641cu7d22u67e5u8be2uff0cu6267u884cu641cu7d22
  if (searchQuery.isNotEmpty) {
    return secureVaultService.searchVaultItems(searchQuery);
  }

  // u5982u679cu6709u9009u62e9u7c7bu578buff0cu8fd4u56deu6307u5b9au7c7bu578bu7684u9879
  if (selectedType != null) {
    return secureVaultService.getVaultItemsByType(selectedType);
  }

  // u5426u5219u8fd4u56deu6240u6709u9879
  return secureVaultService.getVaultItems();
});

/// u6536u85cfu7684u79c1u5bc6u4fe1u606fu9879u5217u8868u63d0u4f9bu8005
final favoriteVaultItemsProvider =
    FutureProvider<List<VaultItemModel>>((ref) async {
  final secureVaultService = ref.watch(secureVaultServiceProvider);
  return secureVaultService.getFavoriteVaultItems();
});

/// u79c1u5bc6u4fe1u606fu9879u64cdu4f5cu72b6u6001u63d0u4f9bu8005
final vaultOperationProvider =
    StateNotifierProvider<VaultOperationNotifier, VaultOperationState>((ref) {
  final secureVaultService = ref.watch(secureVaultServiceProvider);
  return VaultOperationNotifier(secureVaultService, ref);
});

/// u79c1u5bc6u4fe1u606fu9879u64cdu4f5cu72b6u6001u7ba1u7406u5668
class VaultOperationNotifier extends StateNotifier<VaultOperationState> {
  final SecureVaultService _secureVaultService;
  final Ref _ref;

  VaultOperationNotifier(this._secureVaultService, this._ref)
      : super(const VaultOperationState.initial());

  /// u6dfbu52a0u79c1u5bc6u4fe1u606fu9879
  Future<VaultItemModel?> addVaultItem({
    required String title,
    required VaultItemType type,
    required String username,
    required String password,
    String? url,
    String? notes,
    String? icon,
    bool isFavorite = false,
  }) async {
    state = const VaultOperationState.loading();
    try {
      final item = await _secureVaultService.addVaultItem(
        title: title,
        type: type,
        username: username,
        password: password,
        url: url,
        notes: notes,
        icon: icon,
        isFavorite: isFavorite,
      );

      if (item != null) {
        state = const VaultOperationState.success(
            'u79c1u5bc6u4fe1u606fu6dfbu52a0u6210u529f');
        _refreshProviders();
        return item;
      } else {
        state = const VaultOperationState.error(
            'u79c1u5bc6u4fe1u606fu6dfbu52a0u5931u8d25');
        return null;
      }
    } catch (e) {
      state = VaultOperationState.error(
          'u79c1u5bc6u4fe1u606fu6dfbu52a0u5931u8d25: ${e.toString()}');
      return null;
    }
  }

  /// u66f4u65b0u79c1u5bc6u4fe1u606fu9879
  Future<VaultItemModel?> updateVaultItem({
    required String id,
    String? title,
    VaultItemType? type,
    String? username,
    String? password,
    String? url,
    String? notes,
    String? icon,
    bool? isFavorite,
  }) async {
    state = const VaultOperationState.loading();
    try {
      final item = await _secureVaultService.updateVaultItem(
        id: id,
        title: title,
        type: type,
        username: username,
        password: password,
        url: url,
        notes: notes,
        icon: icon,
        isFavorite: isFavorite,
      );

      if (item != null) {
        state = const VaultOperationState.success(
            'u79c1u5bc6u4fe1u606fu66f4u65b0u6210u529f');
        _refreshProviders();
        return item;
      } else {
        state = const VaultOperationState.error(
            'u79c1u5bc6u4fe1u606fu66f4u65b0u5931u8d25');
        return null;
      }
    } catch (e) {
      state = VaultOperationState.error(
          'u79c1u5bc6u4fe1u606fu66f4u65b0u5931u8d25: ${e.toString()}');
      return null;
    }
  }

  /// u5220u9664u79c1u5bc6u4fe1u606fu9879
  Future<bool> deleteVaultItem(String id) async {
    state = const VaultOperationState.loading();
    try {
      final success = await _secureVaultService.deleteVaultItem(id);

      if (success) {
        state = const VaultOperationState.success(
            'u79c1u5bc6u4fe1u606fu5220u9664u6210u529f');
        _refreshProviders();
        return true;
      } else {
        state = const VaultOperationState.error(
            'u79c1u5bc6u4fe1u606fu5220u9664u5931u8d25');
        return false;
      }
    } catch (e) {
      state = VaultOperationState.error(
          'u79c1u5bc6u4fe1u606fu5220u9664u5931u8d25: ${e.toString()}');
      return false;
    }
  }

  /// u5207u6362u6536u85cfu72b6u6001
  Future<VaultItemModel?> toggleFavorite(String id) async {
    try {
      final item = await _secureVaultService.toggleFavorite(id);
      if (item != null) {
        _refreshProviders();
        return item;
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  /// u5237u65b0u63d0u4f9bu8005
  void _refreshProviders() {
    _ref.invalidate(vaultItemsProvider);
    _ref.invalidate(favoriteVaultItemsProvider);
  }
}

/// u79c1u5bc6u4fe1u606fu9879u64cdu4f5cu72b6u6001
class VaultOperationState {
  final bool isLoading;
  final bool isSuccess;
  final String? message;
  final String? error;

  const VaultOperationState({
    required this.isLoading,
    required this.isSuccess,
    this.message,
    this.error,
  });

  /// u521du59cbu72b6u6001
  const VaultOperationState.initial()
      : isLoading = false,
        isSuccess = false,
        message = null,
        error = null;

  /// u52a0u8f7du4e2du72b6u6001
  const VaultOperationState.loading()
      : isLoading = true,
        isSuccess = false,
        message = null,
        error = null;

  /// u6210u529fu72b6u6001
  const VaultOperationState.success(String this.message)
      : isLoading = false,
        isSuccess = true,
        error = null;

  /// u9519u8befu72b6u6001
  const VaultOperationState.error(String this.error)
      : isLoading = false,
        isSuccess = false,
        message = null;
}
